<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>业务记录 - 考勤管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            padding: 30px;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #667eea;
        }
        
        .header h1 {
            color: #667eea;
            font-size: 28px;
        }
        
        .back-btn {
            background: #6c757d;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            text-decoration: none;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .back-btn:hover {
            background: #5a6268;
        }
        
        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            border-bottom: 2px solid #e0e0e0;
        }
        
        .tab {
            padding: 15px 30px;
            background: transparent;
            border: none;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            color: #666;
            transition: all 0.3s;
            border-bottom: 3px solid transparent;
        }
        
        .tab:hover {
            color: #667eea;
        }
        
        .tab.active {
            color: #667eea;
            border-bottom-color: #667eea;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .toolbar {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .filter-row {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr auto auto;
            gap: 15px;
            align-items: end;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-group label {
            margin-bottom: 8px;
            color: #333;
            font-weight: bold;
            font-size: 14px;
        }
        
        .form-group input, .form-group select {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            font-weight: bold;
            white-space: nowrap;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5568d3;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c82333;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        table thead {
            background: #667eea;
            color: white;
        }
        
        table th, table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
            font-size: 14px;
        }
        
        table tbody tr:hover {
            background: #f8f9fa;
        }
        
        .badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .badge-approved {
            background: #d4edda;
            color: #155724;
        }
        
        .badge-pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .badge-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
        }
        
        .modal.show {
            display: flex;
        }
        
        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 15px;
            width: 90%;
            max-width: 500px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
        }
        
        .modal-header {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #667eea;
        }
        
        .modal-header h2 {
            color: #667eea;
            font-size: 22px;
        }
        
        .form-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }
        
        .message.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
            display: block;
        }
        
        .message.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
            display: block;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .empty {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        
        .user-bar {
            background: rgba(102, 126, 234, 0.1);
            padding: 10px 15px;
            border-radius: 10px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .user-bar span {
            color: #667eea;
            font-weight: bold;
        }
        
        .logout-btn {
            padding: 6px 12px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .logout-btn:hover {
            background: #5568d3;
        }
    </style>
    <script src="/js/auth.js"></script>
</head>
<body>
    <div class="container">
        <div class="user-bar">
            <span id="userInfo">👤 加载中...</span>
            <button class="logout-btn" onclick="logout()">🚪 退出</button>
        </div>
        
        <div class="header">
            <h1>📝 业务记录管理</h1>
            <a href="index.html" class="back-btn">← 返回首页</a>
        </div>
        
        <div id="message" class="message"></div>
        
        <!-- Tab 切换 -->
        <div class="tabs">
            <button class="tab active" onclick="switchTab('leave')">📋 请假记录</button>
            <button class="tab" onclick="switchTab('overtime')">⏰ 加班记录</button>
            <button class="tab" onclick="switchTab('travel')">✈️ 出差记录</button>
        </div>
        
        <!-- 请假记录 Tab -->
        <div id="leave-content" class="tab-content active">
            <div class="toolbar">
                <div class="filter-row">
                    <div class="form-group">
                        <label for="leaveEmployeeId">员工</label>
                        <select id="leaveEmployeeId">
                            <option value="">全部员工</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="leaveFromDate">开始日期</label>
                        <input type="date" id="leaveFromDate">
                    </div>
                    <div class="form-group">
                        <label for="leaveToDate">结束日期</label>
                        <input type="date" id="leaveToDate">
                    </div>
                    <button class="btn btn-primary" onclick="loadLeaveRecords()">🔍 查询</button>
                    <button class="btn btn-success" onclick="showLeaveModal()">➕ 新增请假</button>
                </div>
            </div>
            <div id="leaveTableContainer">
                <div class="loading">加载中...</div>
            </div>
        </div>
        
        <!-- 加班记录 Tab -->
        <div id="overtime-content" class="tab-content">
            <div class="toolbar">
                <div class="filter-row">
                    <div class="form-group">
                        <label for="overtimeEmployeeId">员工</label>
                        <select id="overtimeEmployeeId">
                            <option value="">全部员工</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="overtimeFromDate">开始日期</label>
                        <input type="date" id="overtimeFromDate">
                    </div>
                    <div class="form-group">
                        <label for="overtimeToDate">结束日期</label>
                        <input type="date" id="overtimeToDate">
                    </div>
                    <button class="btn btn-primary" onclick="loadOvertimeRecords()">🔍 查询</button>
                    <button class="btn btn-success" onclick="showOvertimeModal()">➕ 新增加班</button>
                </div>
            </div>
            <div id="overtimeTableContainer">
                <div class="loading">加载中...</div>
            </div>
        </div>
        
        <!-- 出差记录 Tab -->
        <div id="travel-content" class="tab-content">
            <div class="toolbar">
                <div class="filter-row">
                    <div class="form-group">
                        <label for="travelEmployeeId">员工</label>
                        <select id="travelEmployeeId">
                            <option value="">全部员工</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="travelFromDate">开始日期</label>
                        <input type="date" id="travelFromDate">
                    </div>
                    <div class="form-group">
                        <label for="travelToDate">结束日期</label>
                        <input type="date" id="travelToDate">
                    </div>
                    <button class="btn btn-primary" onclick="loadTravelRecords()">🔍 查询</button>
                    <button class="btn btn-success" onclick="showTravelModal()">➕ 新增出差</button>
                </div>
            </div>
            <div id="travelTableContainer">
                <div class="loading">加载中...</div>
            </div>
        </div>
    </div>
    
    <!-- 请假记录模态框 -->
    <div id="leaveModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>新增请假记录</h2>
            </div>
            <form id="leaveForm">
                <div class="form-group">
                    <label for="leaveModalEmployeeId">员工 <span style="color: red;">*</span></label>
                    <select id="leaveModalEmployeeId" required>
                        <option value="">请选择员工</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="leaveType">请假类型 <span style="color: red;">*</span></label>
                    <select id="leaveType" required>
                        <option value="ANNUAL">年假</option>
                        <option value="SICK">病假</option>
                        <option value="PERSONAL">事假</option>
                        <option value="COMP_OFF">调休</option>
                        <option value="MATERNITY">产检/产假</option>
                        <option value="OTHER">其他</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="leaveStartTime">开始时间 <span style="color: red;">*</span></label>
                    <input type="datetime-local" id="leaveStartTime" required>
                </div>
                <div class="form-group">
                    <label for="leaveEndTime">结束时间 <span style="color: red;">*</span></label>
                    <input type="datetime-local" id="leaveEndTime" required>
                </div>
                <div class="form-group">
                    <label for="leaveHours">时长(小时) <span style="color: red;">*</span></label>
                    <input type="number" id="leaveHours" step="0.5" min="0" required placeholder="例如：8">
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeLeaveModal()">取消</button>
                    <button type="submit" class="btn btn-success">保存</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 加班记录模态框 -->
    <div id="overtimeModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>新增加班记录</h2>
            </div>
            <form id="overtimeForm">
                <div class="form-group">
                    <label for="overtimeModalEmployeeId">员工 <span style="color: red;">*</span></label>
                    <select id="overtimeModalEmployeeId" required>
                        <option value="">请选择员工</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="overtimeType">加班类型 <span style="color: red;">*</span></label>
                    <select id="overtimeType" required>
                        <option value="WEEKDAY">工作日加班</option>
                        <option value="WEEKEND">周末加班</option>
                        <option value="HOLIDAY">节假日加班</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="overtimeStartTime">开始时间 <span style="color: red;">*</span></label>
                    <input type="datetime-local" id="overtimeStartTime" required>
                </div>
                <div class="form-group">
                    <label for="overtimeEndTime">结束时间 <span style="color: red;">*</span></label>
                    <input type="datetime-local" id="overtimeEndTime" required>
                </div>
                <div class="form-group">
                    <label for="overtimeHours">时长(小时) <span style="color: red;">*</span></label>
                    <input type="number" id="overtimeHours" step="0.5" min="0" required placeholder="例如：2">
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeOvertimeModal()">取消</button>
                    <button type="submit" class="btn btn-success">保存</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 出差记录模态框 -->
    <div id="travelModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>新增出差记录</h2>
            </div>
            <form id="travelForm">
                <div class="form-group">
                    <label for="travelModalEmployeeId">员工 <span style="color: red;">*</span></label>
                    <select id="travelModalEmployeeId" required>
                        <option value="">请选择员工</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="travelPlace">出差地点 <span style="color: red;">*</span></label>
                    <input type="text" id="travelPlace" required placeholder="例如：北京">
                </div>
                <div class="form-group">
                    <label for="travelPurpose">出差事由</label>
                    <input type="text" id="travelPurpose" placeholder="例如：客户拜访">
                </div>
                <div class="form-group">
                    <label for="travelStartTime">开始时间 <span style="color: red;">*</span></label>
                    <input type="datetime-local" id="travelStartTime" required>
                </div>
                <div class="form-group">
                    <label for="travelEndTime">结束时间 <span style="color: red;">*</span></label>
                    <input type="datetime-local" id="travelEndTime" required>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeTravelModal()">取消</button>
                    <button type="submit" class="btn btn-success">保存</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        let employees = [];
        let leaveRecords = [];
        let overtimeRecords = [];
        let travelRecords = [];
        
        // 页面加载时初始化
        window.addEventListener('load', () => {
            loadEmployees();
            setDefaultDates();
            loadLeaveRecords();
        });
        
        // 切换Tab
        function switchTab(tabName) {
            // 移除所有active类
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            
            // 添加active类到当前tab
            event.target.classList.add('active');
            document.getElementById(tabName + '-content').classList.add('active');
            
            // 加载对应数据
            if (tabName === 'leave') {
                loadLeaveRecords();
            } else if (tabName === 'overtime') {
                loadOvertimeRecords();
            } else if (tabName === 'travel') {
                loadTravelRecords();
            }
        }
        
        // 设置默认日期（当月）
        function setDefaultDates() {
            const today = new Date();
            const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
            const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
            
            const firstDayStr = formatDate(firstDay);
            const lastDayStr = formatDate(lastDay);
            
            document.getElementById('leaveFromDate').value = firstDayStr;
            document.getElementById('leaveToDate').value = lastDayStr;
            document.getElementById('overtimeFromDate').value = firstDayStr;
            document.getElementById('overtimeToDate').value = lastDayStr;
            document.getElementById('travelFromDate').value = firstDayStr;
            document.getElementById('travelToDate').value = lastDayStr;
        }
        
        // 格式化日期
        function formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }
        
        // 加载员工列表
        async function loadEmployees() {
            try {
                const response = await fetch('/api/employees');
                const result = await response.json();
                
                if (result.code === 200) {
                    employees = result.data;
                    
                    // 填充所有员工下拉框
                    const selects = [
                        'leaveEmployeeId', 'overtimeEmployeeId', 'travelEmployeeId',
                        'leaveModalEmployeeId', 'overtimeModalEmployeeId', 'travelModalEmployeeId'
                    ];
                    
                    selects.forEach(selectId => {
                        const select = document.getElementById(selectId);
                        // 清空之前的选项（保留第一个）
                        while (select.options.length > 1) {
                            select.remove(1);
                        }
                        // 添加员工选项
                        employees.forEach(emp => {
                            const option = new Option(`${emp.empNo} - ${emp.name}`, emp.id);
                            select.add(option);
                        });
                    });
                }
            } catch (error) {
                console.error('加载员工列表失败:', error);
            }
        }
        
        // ===== 请假记录相关 =====
        async function loadLeaveRecords() {
            const empId = document.getElementById('leaveEmployeeId').value;
            const from = document.getElementById('leaveFromDate').value;
            const to = document.getElementById('leaveToDate').value;
            
            let url = '/api/leaves?';
            if (empId) url += `empId=${empId}&`;
            if (from) url += `from=${from}&`;
            if (to) url += `to=${to}&`;
            
            try {
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.code === 200) {
                    leaveRecords = result.data;
                    renderLeaveTable();
                } else {
                    showMessage('加载失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('网络错误: ' + error.message, 'error');
            }
        }
        
        function renderLeaveTable() {
            const container = document.getElementById('leaveTableContainer');
            
            if (leaveRecords.length === 0) {
                container.innerHTML = '<div class="empty">暂无请假记录</div>';
                return;
            }
            
            const leaveTypeMap = {
                'ANNUAL': '年假', 'SICK': '病假', 'PERSONAL': '事假',
                'COMP_OFF': '调休', 'MATERNITY': '产检/产假', 'OTHER': '其他'
            };
            
            let html = `
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>工号</th>
                            <th>姓名</th>
                            <th>请假类型</th>
                            <th>开始时间</th>
                            <th>结束时间</th>
                            <th>时长(小时)</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            leaveRecords.forEach(record => {
                const statusClass = `badge-${record.status.toLowerCase()}`;
                const statusText = record.status === 'APPROVED' ? '已批准' : record.status === 'PENDING' ? '待审批' : '已拒绝';
                
                html += `
                    <tr>
                        <td>${record.id}</td>
                        <td><strong>${record.empNo || '-'}</strong></td>
                        <td>${record.employeeName || '-'}</td>
                        <td>${leaveTypeMap[record.leaveType] || record.leaveType}</td>
                        <td>${record.startTime || '-'}</td>
                        <td>${record.endTime || '-'}</td>
                        <td>${record.hours}</td>
                        <td><span class="badge ${statusClass}">${statusText}</span></td>
                        <td>${record.createdAt || '-'}</td>
                        <td>
                            <button class="btn btn-danger" style="padding: 5px 10px; font-size: 12px;" onclick="deleteLeaveRecord(${record.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            
            html += '</tbody></table>';
            container.innerHTML = html;
        }
        
        function showLeaveModal() {
            document.getElementById('leaveForm').reset();
            document.getElementById('leaveModal').classList.add('show');
        }
        
        function closeLeaveModal() {
            document.getElementById('leaveModal').classList.remove('show');
        }
        
        document.getElementById('leaveForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const startTime = document.getElementById('leaveStartTime').value.replace('T', ' ') + ':00';
            const endTime = document.getElementById('leaveEndTime').value.replace('T', ' ') + ':00';
            
            const recordData = {
                employeeId: parseInt(document.getElementById('leaveModalEmployeeId').value),
                leaveType: document.getElementById('leaveType').value,
                startTime: startTime,
                endTime: endTime,
                hours: parseFloat(document.getElementById('leaveHours').value),
                status: 'APPROVED'
            };
            
            try {
                const response = await fetch('/api/leaves', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(recordData)
                });
                
                const result = await response.json();
                
                if (result.code === 201) {
                    showMessage('请假记录创建成功', 'success');
                    closeLeaveModal();
                    loadLeaveRecords();
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'error');
            }
        });
        
        async function deleteLeaveRecord(id) {
            if (!confirm('确定要删除该请假记录吗？')) return;
            
            try {
                const response = await fetch(`/api/leaves/${id}`, { method: 'DELETE' });
                const result = await response.json();
                
                if (result.code === 200) {
                    showMessage('删除成功', 'success');
                    loadLeaveRecords();
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                showMessage('删除失败: ' + error.message, 'error');
            }
        }
        
        // ===== 加班记录相关 =====
        async function loadOvertimeRecords() {
            const empId = document.getElementById('overtimeEmployeeId').value;
            const from = document.getElementById('overtimeFromDate').value;
            const to = document.getElementById('overtimeToDate').value;
            
            let url = '/api/overtimes?';
            if (empId) url += `empId=${empId}&`;
            if (from) url += `from=${from}&`;
            if (to) url += `to=${to}&`;
            
            try {
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.code === 200) {
                    overtimeRecords = result.data;
                    renderOvertimeTable();
                } else {
                    showMessage('加载失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('网络错误: ' + error.message, 'error');
            }
        }
        
        function renderOvertimeTable() {
            const container = document.getElementById('overtimeTableContainer');
            
            if (overtimeRecords.length === 0) {
                container.innerHTML = '<div class="empty">暂无加班记录</div>';
                return;
            }
            
            const overtimeTypeMap = {
                'WEEKDAY': '工作日', 'WEEKEND': '周末', 'HOLIDAY': '节假日'
            };
            
            let html = `
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>工号</th>
                            <th>姓名</th>
                            <th>加班类型</th>
                            <th>开始时间</th>
                            <th>结束时间</th>
                            <th>时长(小时)</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            overtimeRecords.forEach(record => {
                const statusClass = `badge-${record.status.toLowerCase()}`;
                const statusText = record.status === 'APPROVED' ? '已批准' : record.status === 'PENDING' ? '待审批' : '已拒绝';
                
                html += `
                    <tr>
                        <td>${record.id}</td>
                        <td><strong>${record.empNo || '-'}</strong></td>
                        <td>${record.employeeName || '-'}</td>
                        <td>${overtimeTypeMap[record.otType] || record.otType}</td>
                        <td>${record.startTime || '-'}</td>
                        <td>${record.endTime || '-'}</td>
                        <td>${record.hours}</td>
                        <td><span class="badge ${statusClass}">${statusText}</span></td>
                        <td>${record.createdAt || '-'}</td>
                        <td>
                            <button class="btn btn-danger" style="padding: 5px 10px; font-size: 12px;" onclick="deleteOvertimeRecord(${record.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            
            html += '</tbody></table>';
            container.innerHTML = html;
        }
        
        function showOvertimeModal() {
            document.getElementById('overtimeForm').reset();
            document.getElementById('overtimeModal').classList.add('show');
        }
        
        function closeOvertimeModal() {
            document.getElementById('overtimeModal').classList.remove('show');
        }
        
        document.getElementById('overtimeForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const startTime = document.getElementById('overtimeStartTime').value.replace('T', ' ') + ':00';
            const endTime = document.getElementById('overtimeEndTime').value.replace('T', ' ') + ':00';
            
            const recordData = {
                employeeId: parseInt(document.getElementById('overtimeModalEmployeeId').value),
                otType: document.getElementById('overtimeType').value,
                startTime: startTime,
                endTime: endTime,
                hours: parseFloat(document.getElementById('overtimeHours').value),
                status: 'APPROVED'
            };
            
            try {
                const response = await fetch('/api/overtimes', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(recordData)
                });
                
                const result = await response.json();
                
                if (result.code === 201) {
                    showMessage('加班记录创建成功', 'success');
                    closeOvertimeModal();
                    loadOvertimeRecords();
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'error');
            }
        });
        
        async function deleteOvertimeRecord(id) {
            if (!confirm('确定要删除该加班记录吗？')) return;
            
            try {
                const response = await fetch(`/api/overtimes/${id}`, { method: 'DELETE' });
                const result = await response.json();
                
                if (result.code === 200) {
                    showMessage('删除成功', 'success');
                    loadOvertimeRecords();
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                showMessage('删除失败: ' + error.message, 'error');
            }
        }
        
        // ===== 出差记录相关 =====
        async function loadTravelRecords() {
            const empId = document.getElementById('travelEmployeeId').value;
            const from = document.getElementById('travelFromDate').value;
            const to = document.getElementById('travelToDate').value;
            
            let url = '/api/travels?';
            if (empId) url += `empId=${empId}&`;
            if (from) url += `from=${from}&`;
            if (to) url += `to=${to}&`;
            
            try {
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.code === 200) {
                    travelRecords = result.data;
                    renderTravelTable();
                } else {
                    showMessage('加载失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('网络错误: ' + error.message, 'error');
            }
        }
        
        function renderTravelTable() {
            const container = document.getElementById('travelTableContainer');
            
            if (travelRecords.length === 0) {
                container.innerHTML = '<div class="empty">暂无出差记录</div>';
                return;
            }
            
            let html = `
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>工号</th>
                            <th>姓名</th>
                            <th>出差地点</th>
                            <th>出差事由</th>
                            <th>开始时间</th>
                            <th>结束时间</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            travelRecords.forEach(record => {
                const statusClass = `badge-${record.status.toLowerCase()}`;
                const statusText = record.status === 'APPROVED' ? '已批准' : record.status === 'PENDING' ? '待审批' : '已拒绝';
                
                html += `
                    <tr>
                        <td>${record.id}</td>
                        <td><strong>${record.empNo || '-'}</strong></td>
                        <td>${record.employeeName || '-'}</td>
                        <td>${record.place}</td>
                        <td>${record.purpose || '-'}</td>
                        <td>${record.startTime || '-'}</td>
                        <td>${record.endTime || '-'}</td>
                        <td><span class="badge ${statusClass}">${statusText}</span></td>
                        <td>${record.createdAt || '-'}</td>
                        <td>
                            <button class="btn btn-danger" style="padding: 5px 10px; font-size: 12px;" onclick="deleteTravelRecord(${record.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            
            html += '</tbody></table>';
            container.innerHTML = html;
        }
        
        function showTravelModal() {
            document.getElementById('travelForm').reset();
            document.getElementById('travelModal').classList.add('show');
        }
        
        function closeTravelModal() {
            document.getElementById('travelModal').classList.remove('show');
        }
        
        document.getElementById('travelForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const startTime = document.getElementById('travelStartTime').value.replace('T', ' ') + ':00';
            const endTime = document.getElementById('travelEndTime').value.replace('T', ' ') + ':00';
            
            const recordData = {
                employeeId: parseInt(document.getElementById('travelModalEmployeeId').value),
                place: document.getElementById('travelPlace').value,
                purpose: document.getElementById('travelPurpose').value || null,
                startTime: startTime,
                endTime: endTime,
                status: 'APPROVED'
            };
            
            try {
                const response = await fetch('/api/travels', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(recordData)
                });
                
                const result = await response.json();
                
                if (result.code === 201) {
                    showMessage('出差记录创建成功', 'success');
                    closeTravelModal();
                    loadTravelRecords();
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'error');
            }
        });
        
        async function deleteTravelRecord(id) {
            if (!confirm('确定要删除该出差记录吗？')) return;
            
            try {
                const response = await fetch(`/api/travels/${id}`, { method: 'DELETE' });
                const result = await response.json();
                
                if (result.code === 200) {
                    showMessage('删除成功', 'success');
                    loadTravelRecords();
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                showMessage('删除失败: ' + error.message, 'error');
            }
        }
        
        // 显示消息
        function showMessage(text, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = text;
            messageDiv.className = 'message ' + type;
            
            setTimeout(() => {
                messageDiv.className = 'message';
            }, 3000);
        }
        
        // 点击模态框外部关闭
        document.querySelectorAll('.modal').forEach(modal => {
            modal.addEventListener('click', (e) => {
                if (e.target === modal) {
                    modal.classList.remove('show');
                }
            });
        });
    </script>
</body>
</html>

